package com.tamir.template.express.handle;

import com.tamir.template.bean.TNode;
import com.tamir.template.config.TemplateNodeTypeConfig;
import com.tamir.template.context.TemplateContext;
import com.tamir.template.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : tanggh
 * @description :〈描述〉
 * @date : 2016/11/8
 */
public class DefaultIfValueHandle extends AbstractExpressValueHandle
{
    /**
     * 获取当前的值
     *
     * @param node
     * @param context
     * @return
     */
    @Override
    public Object getObject(TNode node, TemplateContext context) throws Exception
    {
        Boolean flag = Boolean.FALSE;
        if(node != null && node.getExpressObject() != null){
            Object retValue = TemplateNodeTypeConfig.getInstance().getITExpressValueHandle
                    (node.getExpressObject()).getObject(node.getExpressObject(), context);
            flag = StringUtil.string2Boolean(retValue.toString());
        }
        return flag;
    }

    @Override
    public String generateText(TNode node, TemplateContext context) throws Exception
    {
        StringBuffer textBuffer = new StringBuffer();
        if(node.gettLogicType() != null){
            List<TNode> subList = new ArrayList<TNode>();
            if((Boolean) this.getObject(node, context)){
                subList = node.getSubNodeList();
            }else{
                TNode oppositeNode = node.getOppositeLogicNode();
                if(oppositeNode != null && oppositeNode.getSubNodeList() != null){
                    subList = oppositeNode.getSubNodeList();
                }
            }
            if(!subList.isEmpty()){
                for (TNode subNode : subList){
                    textBuffer.append(TemplateNodeTypeConfig.getInstance().getITExpressValueHandle
                            (subNode).generateText(subNode, context));
                }
            }
        }

        return textBuffer.toString();
    }
}
